/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Faucet;

import javax.microedition.midlet.*;
import org.netbeans.microedition.lcdui.SplashScreen;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*; // Include tutti i "pezzi" del display (Form, Display, ...)
import java.lang.String.*;
import java.util.Date.*;
import java.util.Calendar;
import org.netbeans.microedition.lcdui.LoginScreen;
/**
 * @author luca
 */
public class Faucet extends MIDlet implements CommandListener {

    public String VERSION = "1.2.1";
    public int KVIDEO = 1;
    public int KRADIO = 2;
    public int DefaultRecType = KVIDEO;
    public int MAXCHANNELS = 200;
    public String REC_VIDEO= "video";
    public String REC_RADIO = "radio";
    public String RecType = REC_VIDEO; // Default.
    
    // 1.2.1:
    // ripristinata compilabilita';
    // Aggiunti canali radio;
    // Aggiunte liste canali in risorse.
    // Aggiunte in risorse TUTTE le liste.
    // Aggiunta bozza di scaricamento programmazioni esistenti. Risposta troncata se troppo lunga.
    
    // 1.1.1: 
    // corretto bug MTV--> Mtv ; 
    private boolean midletPaused = false;
    public String user, pass;
    String canale;
    String titolo;
    Integer formato;
    int ripetizione;
    int conservazione;
    String StringaInizio, StringaFine;
    int NumTV, NumRadio;
    String TVChannelName[] = new String[MAXCHANNELS];
    String RadioChannelName[] = new String[MAXCHANNELS];
    Integer ConvForm[] = new Integer[10]; // Array conversione tabella formati registrazione.

    

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Command exitCommand;
    private Command cmdConfirm;
    private Command cmdAbout1;
    private Command cmdAbout;
    private Command cmdSend;
    private Command exitCommand1;
    private Command cmdRipeti;
    private Command cmdCorreggi;
    private Command cmdTV;
    private Command cmdRetrieve;
    private Command cmdRADIO;
    private Command backCommand;
    private Command cmdLogin;
    private Command screenCommand;
    private Alert alAbout;
    private SplashScreen splStart;
    private Form frmImmissioneDati;
    private ChoiceGroup lstCanale;
    private ChoiceGroup lstFormato;
    private DateField dtEnd;
    private TextField txtTitolo;
    private DateField dtStart;
    private ChoiceGroup lstRipetizioni;
    private ChoiceGroup lstConservazione;
    private TextBox txtRiepilogo;
    private TextBox txtRisultato;
    private LoginScreen loginScreen;
    private Alert alTipoCanale;
    private SplashScreen splTest;
    private SplashScreen spltest2;
    private TextBox frmInfo;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The Faucet constructor.
     */
    public Faucet() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getFrmImmissioneDati());  // Va mostrato subito, senno' c'e' un errore di runtime nell'aggiornare le liste!
        switchDisplayable(null, getFrmInfo());//GEN-LINE:|3-startMIDlet|1|3-postAction
        frmInfo.setString("Caricamento dati login...");
        getLogin();
        frmInfo.setString("Caricamento canali...");
        getChannels();
        frmInfo.setString("Caricamento liste...");
        getOtherLists();
        frmInfo.setString("Impostazione canali...");
        impostaCanali(DefaultRecType);
        switchDisplayable(null, getFrmImmissioneDati()); // Va rimostrato, dopo l'alert.         
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == frmImmissioneDati) {//GEN-BEGIN:|7-commandAction|1|36-preAction
            if (command == cmdAbout1) {//GEN-END:|7-commandAction|1|36-preAction
                // write pre-action user code here
                switchDisplayable(getAlAbout(), getFrmImmissioneDati());//GEN-LINE:|7-commandAction|2|36-postAction
                // write post-action user code here
            } else if (command == cmdConfirm) {//GEN-LINE:|7-commandAction|3|32-preAction
                frmInfo.setString("Controllo dati inseriti...");
                switchDisplayable(null, getFrmInfo());//GEN-LINE:|7-commandAction|4|32-postAction
                estrazioneDati();
                switchDisplayable(null, getTxtRiepilogo()); // Visualizza prima per evitare errore runtime.
                frmInfo.setString("Visualizzo dati inseriti:"); 
                switchDisplayable(null, getFrmInfo());
                aggiornaFormConferma();
                switchDisplayable(null, getTxtRiepilogo()); // Rivisualizza dopo info
            } else if (command == cmdRADIO) {//GEN-LINE:|7-commandAction|5|105-preAction
                getAlTipoCanale().setString("Impostato: Radio");
                lstCanale.deleteAll(); 
                impostaCanali(KRADIO);
                RecType = REC_RADIO;
                switchDisplayable(getAlTipoCanale(), getFrmImmissioneDati());//GEN-LINE:|7-commandAction|6|105-postAction
               
            } else if (command == cmdRetrieve) {//GEN-LINE:|7-commandAction|7|109-preAction
               // switchDisplayable(null, getTxtRisultato());
                frmInfo.setString("Invio richiesta");
                switchDisplayable(null, getTxtRisultato());//GEN-LINE:|7-commandAction|8|109-postAction
                switchDisplayable(null, getFrmInfo());
                estrazioneDati(); // Dummy
                InvioRichiesta("http://www.vcast.it/faucetpvr/csp/server_rest.php?method=serve_list&uname=aUsername&pswd=aPassword");
                switchDisplayable(null, getTxtRisultato());
            } else if (command == cmdTV) {//GEN-LINE:|7-commandAction|9|102-preAction
                getAlTipoCanale().setString("Impostato: TV");
                lstCanale.deleteAll();                
                impostaCanali(KVIDEO);
                RecType = REC_VIDEO;
                switchDisplayable(getAlTipoCanale(), getFrmImmissioneDati());//GEN-LINE:|7-commandAction|10|102-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|11|140-preAction
        } else if (displayable == frmInfo) {
            if (command == screenCommand) {//GEN-END:|7-commandAction|11|140-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|12|140-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|13|112-preAction
        } else if (displayable == loginScreen) {
            if (command == LoginScreen.LOGIN_COMMAND) {//GEN-END:|7-commandAction|13|112-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|14|112-postAction
                // write post-action user code here
            } else if (command == backCommand) {//GEN-LINE:|7-commandAction|15|117-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|16|117-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|17|24-preAction
        } else if (displayable == splStart) {
            if (command == SplashScreen.DISMISS_COMMAND) {//GEN-END:|7-commandAction|17|24-preAction
//GEN-LINE:|7-commandAction|18|24-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|19|122-preAction
        } else if (displayable == splTest) {
            if (command == SplashScreen.DISMISS_COMMAND) {//GEN-END:|7-commandAction|19|122-preAction
                // write pre-action user code here
                switchDisplayable(null, getTxtRiepilogo());//GEN-LINE:|7-commandAction|20|122-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|21|125-preAction
        } else if (displayable == spltest2) {
            if (command == SplashScreen.DISMISS_COMMAND) {//GEN-END:|7-commandAction|21|125-preAction
                // write pre-action user code here
                switchDisplayable(null, getTxtRisultato());//GEN-LINE:|7-commandAction|22|125-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|23|66-preAction
        } else if (displayable == txtRiepilogo) {
            if (command == cmdAbout) {//GEN-END:|7-commandAction|23|66-preAction
                // write pre-action user code here
                switchDisplayable(getAlAbout(), getTxtRiepilogo());//GEN-LINE:|7-commandAction|24|66-postAction
                // write post-action user code here
            } else if (command == cmdCorreggi) {//GEN-LINE:|7-commandAction|25|93-preAction
                // write pre-action user code here
                switchDisplayable(null, getFrmImmissioneDati());//GEN-LINE:|7-commandAction|26|93-postAction
                // write post-action user code here
            } else if (command == cmdSend) {//GEN-LINE:|7-commandAction|27|78-preAction
                frmInfo.setString("Attendere...");
                switchDisplayable(null, getTxtRisultato()); // Previsualizza
                switchDisplayable(null, getFrmInfo());//GEN-LINE:|7-commandAction|28|78-postAction
                InvioRichiesta("http://www.vcast.it/faucetpvr/csp/server_rest.php?method=serve_insert&uname=aUsername&pswd=aPassword&param1=channelType&param2=TVChannelName&param3=title&param4=format&param5=fromTime&param6=toTime&param7=repeat&param8=retention");
                switchDisplayable(null, getFrmInfo());
                frmInfo.setString("Richiesta inviata...");
                switchDisplayable(null, getTxtRisultato());
            } else if (command == exitCommand) {//GEN-LINE:|7-commandAction|29|95-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|30|95-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|31|144-preAction
        } else if (displayable == txtRisultato) {
            if (command == cmdRetrieve) {//GEN-END:|7-commandAction|31|144-preAction
                // write pre-action user code here
                switchDisplayable(null, getTxtRisultato());//GEN-LINE:|7-commandAction|32|144-postAction
                frmInfo.setString("Invio richiesta");
                switchDisplayable(null, getFrmInfo());
                estrazioneDati(); // Dummy
                InvioRichiesta("http://www.vcast.it/faucetpvr/csp/server_rest.php?method=serve_list&uname=aUsername&pswd=aPassword");
                switchDisplayable(null, getTxtRisultato());
            } else if (command == cmdRipeti) {//GEN-LINE:|7-commandAction|33|83-preAction
                // write pre-action user code here
                switchDisplayable(null, getFrmImmissioneDati());//GEN-LINE:|7-commandAction|34|83-postAction
                // write post-action user code here
            } else if (command == exitCommand1) {//GEN-LINE:|7-commandAction|35|85-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|36|85-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|37|7-postCommandAction
        }//GEN-END:|7-commandAction|37|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|38|
    //</editor-fold>//GEN-END:|7-commandAction|38|




    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            exitCommand = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return exitCommand;
    }
    //</editor-fold>//GEN-END:|18-getter|2|





    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdConfirm ">//GEN-BEGIN:|31-getter|0|31-preInit
    /**
     * Returns an initiliazed instance of cmdConfirm component.
     * @return the initialized component instance
     */
    public Command getCmdConfirm() {
        if (cmdConfirm == null) {//GEN-END:|31-getter|0|31-preInit
            // write pre-init user code here
            cmdConfirm = new Command("Conferma", Command.OK, 0);//GEN-LINE:|31-getter|1|31-postInit
            // write post-init user code here
        }//GEN-BEGIN:|31-getter|2|
        return cmdConfirm;
    }
    //</editor-fold>//GEN-END:|31-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdAbout1 ">//GEN-BEGIN:|35-getter|0|35-preInit
    /**
     * Returns an initiliazed instance of cmdAbout1 component.
     * @return the initialized component instance
     */
    public Command getCmdAbout1() {
        if (cmdAbout1 == null) {//GEN-END:|35-getter|0|35-preInit
            // write pre-init user code here
            cmdAbout1 = new Command("ABOUT", Command.SCREEN, 0);//GEN-LINE:|35-getter|1|35-postInit
            // write post-init user code here
        }//GEN-BEGIN:|35-getter|2|
        return cmdAbout1;
    }
    //</editor-fold>//GEN-END:|35-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: alAbout ">//GEN-BEGIN:|21-getter|0|21-preInit
    /**
     * Returns an initiliazed instance of alAbout component.
     * @return the initialized component instance
     */
    public Alert getAlAbout() {
        if (alAbout == null) {//GEN-END:|21-getter|0|21-preInit
            alAbout.setString(VERSION);
            alAbout = new Alert("alert", "Faucet PVR v 1.1.1", null, null);//GEN-BEGIN:|21-getter|1|21-postInit
            alAbout.setTimeout(Alert.FOREVER);//GEN-END:|21-getter|1|21-postInit

        }//GEN-BEGIN:|21-getter|2|
        return alAbout;
    }
    //</editor-fold>//GEN-END:|21-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: splStart ">//GEN-BEGIN:|22-getter|0|22-preInit
    /**
     * Returns an initiliazed instance of splStart component.
     * @return the initialized component instance
     */
    public SplashScreen getSplStart() {
        if (splStart == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
            splStart = new SplashScreen(getDisplay());//GEN-BEGIN:|22-getter|1|22-postInit
            splStart.setTitle("Faucet PVR frontend");
            splStart.setCommandListener(this);
            splStart.setText("by Luca Cassioli 2008");
            splStart.setTimeout(10);//GEN-END:|22-getter|1|22-postInit
            // write post-init user code here
        }//GEN-BEGIN:|22-getter|2|
        return splStart;
    }
    //</editor-fold>//GEN-END:|22-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: frmImmissioneDati ">//GEN-BEGIN:|28-getter|0|28-preInit
    /**
     * Returns an initiliazed instance of frmImmissioneDati component.
     * @return the initialized component instance
     */
    public Form getFrmImmissioneDati() {
        if (frmImmissioneDati == null) {//GEN-END:|28-getter|0|28-preInit
            // write pre-init user code here
            frmImmissioneDati = new Form("Immettere dati registrazione", new Item[] { getTxtTitolo(), getLstCanale(), getDtStart(), getDtEnd(), getLstFormato(), getLstRipetizioni(), getLstConservazione() });//GEN-BEGIN:|28-getter|1|28-postInit
            frmImmissioneDati.addCommand(getCmdConfirm());
            frmImmissioneDati.addCommand(getCmdTV());
            frmImmissioneDati.addCommand(getCmdRADIO());
            frmImmissioneDati.addCommand(getCmdRetrieve());
            frmImmissioneDati.addCommand(getCmdAbout1());
            frmImmissioneDati.setCommandListener(this);//GEN-END:|28-getter|1|28-postInit
            // write post-init user code here
        }//GEN-BEGIN:|28-getter|2|
        return frmImmissioneDati;
    }
    //</editor-fold>//GEN-END:|28-getter|2|







    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: lstCanale ">//GEN-BEGIN:|49-getter|0|49-preInit
    /**
     * Returns an initiliazed instance of lstCanale component.
     * @return the initialized component instance
     */
    public ChoiceGroup getLstCanale() {
        if (lstCanale == null) {//GEN-END:|49-getter|0|49-preInit
            lstCanale = new ChoiceGroup("Canale", Choice.POPUP);//GEN-BEGIN:|49-getter|1|49-postInit
            lstCanale.setSelectedFlags(new boolean[] {  });//GEN-END:|49-getter|1|49-postInit
        }//GEN-BEGIN:|49-getter|2|
        return lstCanale;
    }
    //</editor-fold>//GEN-END:|49-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdAbout ">//GEN-BEGIN:|65-getter|0|65-preInit
    /**
     * Returns an initiliazed instance of cmdAbout component.
     * @return the initialized component instance
     */
    public Command getCmdAbout() {
        if (cmdAbout == null) {//GEN-END:|65-getter|0|65-preInit
            // write pre-init user code here
            cmdAbout = new Command("About", Command.SCREEN, 0);//GEN-LINE:|65-getter|1|65-postInit
            // write post-init user code here
        }//GEN-BEGIN:|65-getter|2|
        return cmdAbout;
    }
    //</editor-fold>//GEN-END:|65-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: txtRiepilogo ">//GEN-BEGIN:|57-getter|0|57-preInit
    /**
     * Returns an initiliazed instance of txtRiepilogo component.
     * @return the initialized component instance
     */
    public TextBox getTxtRiepilogo() {
        if (txtRiepilogo == null) {//GEN-END:|57-getter|0|57-preInit
            // write pre-init user code here
            txtRiepilogo = new TextBox("Riepilogo dati inseriti", "---\n", 5000, TextField.ANY);//GEN-BEGIN:|57-getter|1|57-postInit
            txtRiepilogo.addCommand(getCmdSend());
            txtRiepilogo.addCommand(getCmdCorreggi());
            txtRiepilogo.addCommand(getCmdAbout());
            txtRiepilogo.addCommand(getExitCommand());
            txtRiepilogo.setCommandListener(this);//GEN-END:|57-getter|1|57-postInit
            // write post-init user code here
        }//GEN-BEGIN:|57-getter|2|
        return txtRiepilogo;
    }
    //</editor-fold>//GEN-END:|57-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: lstFormato ">//GEN-BEGIN:|70-getter|0|70-preInit
    /**
     * Returns an initiliazed instance of lstFormato component.
     * @return the initialized component instance
     */
    public ChoiceGroup getLstFormato() {
        if (lstFormato == null) {//GEN-END:|70-getter|0|70-preInit
            // write pre-init user code here
            lstFormato = new ChoiceGroup("Formato registrazione", Choice.POPUP);//GEN-BEGIN:|70-getter|1|70-postInit
            lstFormato.setFitPolicy(Choice.TEXT_WRAP_DEFAULT);
            lstFormato.setSelectedFlags(new boolean[] {  });//GEN-END:|70-getter|1|70-postInit
            // write post-init user code here
        }//GEN-BEGIN:|70-getter|2|
        return lstFormato;
    }
    //</editor-fold>//GEN-END:|70-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: txtTitolo ">//GEN-BEGIN:|74-getter|0|74-preInit
    /**
     * Returns an initiliazed instance of txtTitolo component.
     * @return the initialized component instance
     */
    public TextField getTxtTitolo() {
        if (txtTitolo == null) {//GEN-END:|74-getter|0|74-preInit
            // write pre-init user code here
            txtTitolo = new TextField("Titolo", "[attendere prego]", 32, TextField.ANY);//GEN-LINE:|74-getter|1|74-postInit
            // write post-init user code here
        }//GEN-BEGIN:|74-getter|2|
        return txtTitolo;
    }
    //</editor-fold>//GEN-END:|74-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: dtStart ">//GEN-BEGIN:|75-getter|0|75-preInit
    /**
     * Returns an initiliazed instance of dtStart component.
     * @return the initialized component instance
     */
    public DateField getDtStart() {
        if (dtStart == null) {//GEN-END:|75-getter|0|75-preInit
            // write pre-init user code here
            dtStart = new DateField("Inizio", DateField.DATE_TIME);//GEN-BEGIN:|75-getter|1|75-postInit
            dtStart.setDate(new java.util.Date(System.currentTimeMillis()+60000));//GEN-END:|75-getter|1|75-postInit
            // write post-init user code here
        }//GEN-BEGIN:|75-getter|2|
        return dtStart;
    }
    //</editor-fold>//GEN-END:|75-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: dtEnd ">//GEN-BEGIN:|76-getter|0|76-preInit
    /**
     * Returns an initiliazed instance of dtEnd component.
     * @return the initialized component instance
     */
    public DateField getDtEnd() {
        if (dtEnd == null) {//GEN-END:|76-getter|0|76-preInit
            // write pre-init user code here
            dtEnd = new DateField("Fine", DateField.DATE_TIME);//GEN-BEGIN:|76-getter|1|76-postInit
            dtEnd.setDate(new java.util.Date(System.currentTimeMillis()+60000+600000));//GEN-END:|76-getter|1|76-postInit
            // write post-init user code here
        }//GEN-BEGIN:|76-getter|2|
        return dtEnd;
    }
    //</editor-fold>//GEN-END:|76-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdSend ">//GEN-BEGIN:|77-getter|0|77-preInit
    /**
     * Returns an initiliazed instance of cmdSend component.
     * @return the initialized component instance
     */
    public Command getCmdSend() {
        if (cmdSend == null) {//GEN-END:|77-getter|0|77-preInit
            // write pre-init user code here
            cmdSend = new Command("Invia", Command.OK, 0);//GEN-LINE:|77-getter|1|77-postInit
            // write post-init user code here
        }//GEN-BEGIN:|77-getter|2|
        return cmdSend;
    }
    //</editor-fold>//GEN-END:|77-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdRipeti ">//GEN-BEGIN:|82-getter|0|82-preInit
    /**
     * Returns an initiliazed instance of cmdRipeti component.
     * @return the initialized component instance
     */
    public Command getCmdRipeti() {
        if (cmdRipeti == null) {//GEN-END:|82-getter|0|82-preInit
            // write pre-init user code here
            cmdRipeti = new Command("Inserimento dati", Command.SCREEN, 0);//GEN-LINE:|82-getter|1|82-postInit
            // write post-init user code here
        }//GEN-BEGIN:|82-getter|2|
        return cmdRipeti;
    }
    //</editor-fold>//GEN-END:|82-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand1 ">//GEN-BEGIN:|84-getter|0|84-preInit
    /**
     * Returns an initiliazed instance of exitCommand1 component.
     * @return the initialized component instance
     */
    public Command getExitCommand1() {
        if (exitCommand1 == null) {//GEN-END:|84-getter|0|84-preInit
            // write pre-init user code here
            exitCommand1 = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|84-getter|1|84-postInit
            // write post-init user code here
        }//GEN-BEGIN:|84-getter|2|
        return exitCommand1;
    }
    //</editor-fold>//GEN-END:|84-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: txtRisultato ">//GEN-BEGIN:|80-getter|0|80-preInit
    /**
     * Returns an initiliazed instance of txtRisultato component.
     * @return the initialized component instance
     */
    public TextBox getTxtRisultato() {
        if (txtRisultato == null) {//GEN-END:|80-getter|0|80-preInit
            // write pre-init user code here
            txtRisultato = new TextBox("Risultato operazione", "-\n", 10000, TextField.ANY);//GEN-BEGIN:|80-getter|1|80-postInit
            txtRisultato.addCommand(getCmdRipeti());
            txtRisultato.addCommand(getExitCommand1());
            txtRisultato.addCommand(getCmdRetrieve());
            txtRisultato.setCommandListener(this);//GEN-END:|80-getter|1|80-postInit
            // write post-init user code here
        }//GEN-BEGIN:|80-getter|2|
        return txtRisultato;
    }
    //</editor-fold>//GEN-END:|80-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: lstRipetizioni ">//GEN-BEGIN:|88-getter|0|88-preInit
    /**
     * Returns an initiliazed instance of lstRipetizioni component.
     * @return the initialized component instance
     */
    public ChoiceGroup getLstRipetizioni() {
        if (lstRipetizioni == null) {//GEN-END:|88-getter|0|88-preInit
            // write pre-init user code here
            lstRipetizioni = new ChoiceGroup("Ripetizioni", Choice.POPUP);//GEN-BEGIN:|88-getter|1|88-postInit
            lstRipetizioni.setSelectedFlags(new boolean[] {  });//GEN-END:|88-getter|1|88-postInit
            // write post-init user code here
        }//GEN-BEGIN:|88-getter|2|
        return lstRipetizioni;
    }
    //</editor-fold>//GEN-END:|88-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: lstConservazione ">//GEN-BEGIN:|90-getter|0|90-preInit
    /**
     * Returns an initiliazed instance of lstConservazione component.
     * @return the initialized component instance
     */
    public ChoiceGroup getLstConservazione() {
        if (lstConservazione == null) {//GEN-END:|90-getter|0|90-preInit
            // write pre-init user code here
            lstConservazione = new ChoiceGroup("Conservazione", Choice.POPUP);//GEN-BEGIN:|90-getter|1|90-postInit
            lstConservazione.setSelectedFlags(new boolean[] {  });//GEN-END:|90-getter|1|90-postInit
            // write post-init user code here
        }//GEN-BEGIN:|90-getter|2|
        return lstConservazione;
    }
    //</editor-fold>//GEN-END:|90-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdCorreggi ">//GEN-BEGIN:|92-getter|0|92-preInit
    /**
     * Returns an initiliazed instance of cmdCorreggi component.
     * @return the initialized component instance
     */
    public Command getCmdCorreggi() {
        if (cmdCorreggi == null) {//GEN-END:|92-getter|0|92-preInit
            // write pre-init user code here
            cmdCorreggi = new Command("Modifica dati", Command.SCREEN, 0);//GEN-LINE:|92-getter|1|92-postInit
            // write post-init user code here
        }//GEN-BEGIN:|92-getter|2|
        return cmdCorreggi;
    }
    //</editor-fold>//GEN-END:|92-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdTV ">//GEN-BEGIN:|101-getter|0|101-preInit
    /**
     * Returns an initiliazed instance of cmdTV component.
     * @return the initialized component instance
     */
    public Command getCmdTV() {
        if (cmdTV == null) {//GEN-END:|101-getter|0|101-preInit
            // write pre-init user code here
            cmdTV = new Command("TV", Command.OK, 0);//GEN-LINE:|101-getter|1|101-postInit
            // write post-init user code here
        }//GEN-BEGIN:|101-getter|2|
        return cmdTV;
    }
    //</editor-fold>//GEN-END:|101-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdRADIO ">//GEN-BEGIN:|104-getter|0|104-preInit
    /**
     * Returns an initiliazed instance of cmdRADIO component.
     * @return the initialized component instance
     */
    public Command getCmdRADIO() {
        if (cmdRADIO == null) {//GEN-END:|104-getter|0|104-preInit
            // write pre-init user code here
            cmdRADIO = new Command("Radio", Command.OK, 0);//GEN-LINE:|104-getter|1|104-postInit
            // write post-init user code here
        }//GEN-BEGIN:|104-getter|2|
        return cmdRADIO;
    }
    //</editor-fold>//GEN-END:|104-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: alTipoCanale ">//GEN-BEGIN:|107-getter|0|107-preInit
    /**
     * Returns an initiliazed instance of alTipoCanale component.
     * @return the initialized component instance
     */
    public Alert getAlTipoCanale() {
        if (alTipoCanale == null) {//GEN-END:|107-getter|0|107-preInit
            // write pre-init user code here
            alTipoCanale = new Alert("Impostazione tipo canale", "Tipo canale impostato:", null, null);//GEN-BEGIN:|107-getter|1|107-postInit
            alTipoCanale.setTimeout(Alert.FOREVER);//GEN-END:|107-getter|1|107-postInit
            // write post-init user code here
        }//GEN-BEGIN:|107-getter|2|
        return alTipoCanale;
    }
    //</editor-fold>//GEN-END:|107-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdRetrieve ">//GEN-BEGIN:|108-getter|0|108-preInit
    /**
     * Returns an initiliazed instance of cmdRetrieve component.
     * @return the initialized component instance
     */
    public Command getCmdRetrieve() {
        if (cmdRetrieve == null) {//GEN-END:|108-getter|0|108-preInit
            // write pre-init user code here
            cmdRetrieve = new Command("Mostra programmazioni", Command.SCREEN, 0);//GEN-LINE:|108-getter|1|108-postInit
            // write post-init user code here
        }//GEN-BEGIN:|108-getter|2|
        return cmdRetrieve;
    }
    //</editor-fold>//GEN-END:|108-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cmdLogin ">//GEN-BEGIN:|113-getter|0|113-preInit
    /**
     * Returns an initiliazed instance of cmdLogin component.
     * @return the initialized component instance
     */
    public Command getCmdLogin() {
        if (cmdLogin == null) {//GEN-END:|113-getter|0|113-preInit
            // write pre-init user code here
            cmdLogin = new Command("Login", Command.SCREEN, 0);//GEN-LINE:|113-getter|1|113-postInit
            // write post-init user code here
        }//GEN-BEGIN:|113-getter|2|
        return cmdLogin;
    }
    //</editor-fold>//GEN-END:|113-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|116-getter|0|116-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|116-getter|0|116-preInit
            // write pre-init user code here
            backCommand = new Command("Back", Command.BACK, 0);//GEN-LINE:|116-getter|1|116-postInit
            // write post-init user code here
        }//GEN-BEGIN:|116-getter|2|
        return backCommand;
    }
    //</editor-fold>//GEN-END:|116-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: loginScreen ">//GEN-BEGIN:|111-getter|0|111-preInit
    /**
     * Returns an initiliazed instance of loginScreen component.
     * @return the initialized component instance
     */
    public LoginScreen getLoginScreen() {
        if (loginScreen == null) {//GEN-END:|111-getter|0|111-preInit
            // write pre-init user code here
            loginScreen = new LoginScreen(getDisplay());//GEN-BEGIN:|111-getter|1|111-postInit
            loginScreen.setLabelTexts("Username", "Password");
            loginScreen.setTitle("loginScreen");
            loginScreen.addCommand(LoginScreen.LOGIN_COMMAND);
            loginScreen.addCommand(getBackCommand());
            loginScreen.setCommandListener(this);
            loginScreen.setBGColor(-3355444);
            loginScreen.setFGColor(0);
            loginScreen.setUseLoginButton(false);
            loginScreen.setLoginButtonText("Login");//GEN-END:|111-getter|1|111-postInit
            // write post-init user code here
        }//GEN-BEGIN:|111-getter|2|
        return loginScreen;
    }
    //</editor-fold>//GEN-END:|111-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: splTest ">//GEN-BEGIN:|121-getter|0|121-preInit
    /**
     * Returns an initiliazed instance of splTest component.
     * @return the initialized component instance
     */
    public SplashScreen getSplTest() {
        if (splTest == null) {//GEN-END:|121-getter|0|121-preInit
            // write pre-init user code here
            splTest = new SplashScreen(getDisplay());//GEN-BEGIN:|121-getter|1|121-postInit
            splTest.setTitle("Attendere prego");
            splTest.setCommandListener(this);
            splTest.setText("Elaboro...");
            splTest.setTimeout(1000);//GEN-END:|121-getter|1|121-postInit
            // write post-init user code here
        }//GEN-BEGIN:|121-getter|2|
        return splTest;
    }
    //</editor-fold>//GEN-END:|121-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: spltest2 ">//GEN-BEGIN:|124-getter|0|124-preInit
    /**
     * Returns an initiliazed instance of spltest2 component.
     * @return the initialized component instance
     */
    public SplashScreen getSpltest2() {
        if (spltest2 == null) {//GEN-END:|124-getter|0|124-preInit
            // write pre-init user code here
            spltest2 = new SplashScreen(getDisplay());//GEN-BEGIN:|124-getter|1|124-postInit
            spltest2.setTitle("Attendere risposta");
            spltest2.setCommandListener(this);
            spltest2.setText("Invio dati server.");
            spltest2.setTimeout(1000);//GEN-END:|124-getter|1|124-postInit
            // write post-init user code here
        }//GEN-BEGIN:|124-getter|2|
        return spltest2;
    }
    //</editor-fold>//GEN-END:|124-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: screenCommand ">//GEN-BEGIN:|129-getter|0|129-preInit
    /**
     * Returns an initiliazed instance of screenCommand component.
     * @return the initialized component instance
     */
    public Command getScreenCommand() {
        if (screenCommand == null) {//GEN-END:|129-getter|0|129-preInit
            // write pre-init user code here
            screenCommand = new Command("Screen", Command.SCREEN, 0);//GEN-LINE:|129-getter|1|129-postInit
            // write post-init user code here
        }//GEN-BEGIN:|129-getter|2|
        return screenCommand;
    }
    //</editor-fold>//GEN-END:|129-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: frmInfo ">//GEN-BEGIN:|138-getter|0|138-preInit
    /**
     * Returns an initiliazed instance of frmInfo component.
     * @return the initialized component instance
     */
    public TextBox getFrmInfo() {
        if (frmInfo == null) {//GEN-END:|138-getter|0|138-preInit
            // write pre-init user code here
            frmInfo = new TextBox("Informazione", "[niente]", 100, TextField.ANY);//GEN-BEGIN:|138-getter|1|138-postInit
            frmInfo.addCommand(getScreenCommand());
            frmInfo.setCommandListener(this);//GEN-END:|138-getter|1|138-postInit
            // write post-init user code here
        }//GEN-BEGIN:|138-getter|2|
        return frmInfo;
    }
    //</editor-fold>//GEN-END:|138-getter|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

private void InvioRichiesta(String url) {
        {
            // Code from:
            // http://www.j2mecodex.com/source/corej2me_book/examples/ch14/viewfile/viewfile.java.txt

            HttpConnection http = null;
            InputStream iStrm = null;

            /* http://www.vcast.it/faucetpvr/csp/server_rest.php?method=serve_insert&
            uname=aUsername&
            pswd=aPassword&
            param1=channelType& (video/radio)
            param2=TVChannelName& (nome canale)
            param3=title& (titolo qualunque)
            param4=format& (1=IPOD, 2=PSP, 3=3GP, 4=DIVX, 5=MP3, 6=OggVorbis, 7=AppleTV)
            param5=fromTime& (yyyy-mm-dd hh:mm:ss)
            param6=toTime& (yyyy-mm-dd hh:mm:ss)
            param7=repeat& (1=no, 2=giorno, 3=settimana, 4=lun-ven, 5=lun-sab)
            param8=retention (numero giorni, 1..3)
             */

            //String url = "http://www.vcast.it/faucetpvr/csp/server_rest.php?method=serve_insert&uname=aUsername&pswd=aPassword&param1=channelType&param2=TVChannelName&param3=title&param4=format&param5=fromTime&param6=toTime&param7=repeat&param8=retention";

            url = replace(url, "aUsername", user);
            url = replace(url, "aPassword", pass);
            url = replace(url, "title", titolo);
            url = replace(url, "channelType", RecType);
            url = replace(url, "TVChannelName", canale);
            url = replace(url, "format", "" + convert(formato));
            url = replace(url, "fromTime", StringaInizio);
            url = replace(url, "toTime", StringaFine);
            url = replace(url, "repeat", "" + ripetizione);
            url = replace(url, "retention", "" + conservazione);
            url = replace(url," ","_"); // Spazi non ammessi!
            System.out.println("URL INVIATO: " + url);

            try {
                // Create the connection
                txtRisultato.setString("Creazione connessione...");
                    http = (HttpConnection) Connector.open(url);


                //----------------
                // Client Request
                //----------------
                // 1) Send request method
                http.setRequestMethod(HttpConnection.POST);

                // 2) Send header information (this header is optional)
                http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");

                // If you experience IO problems, try 
                // removing the comment from the following line
                //http.setRequestProperty("Connection", "close");      

                //----------------
                // Server Response
                //----------------

                // 1) Get status Line
                txtRisultato.setString(txtRisultato.getString()+"Url inviato:\n"+url);
                txtRisultato.setString(txtRisultato.getString()+"\nLettura risposta...");
                System.out.println("Msg: " + http.getResponseMessage());
                System.out.println("Code: " + http.getResponseCode());

                // 2) Get header information 
                txtRisultato.setString(txtRisultato.getString()+"\nRisultato:" + http.getResponseCode());
                if (http.getResponseCode() == HttpConnection.HTTP_OK) {
                    // 3) Get data (show the file contents)
                    txtRisultato.setString(txtRisultato.getString()+"\nConnessione riuscita. Leggo risposta...");
                    String str;
                    iStrm = http.openInputStream();
                    int length = (int) http.getLength();
                    if (length != -1) {
                        txtRisultato.setString(txtRisultato.getString()+"\nLeggo " + length + " bytes...");
                        // Read data in one chunk
                        byte serverData[] = new byte[length];
                        iStrm.read(serverData);
                        str = new String(serverData);
                        if (str.length()<= txtRisultato.getMaxSize()) {
                            txtRisultato.setString(txtRisultato.getString()+"\n\n****** Risposta server: " + str + "****** \n");
                        } else {
                             txtRisultato.setString(txtRisultato.getString()+"\n\n****** Risposta server TROPPO LUNGA per essere mostrata! ****** \n");
                        }
                        txtRisultato.setString(txtRisultato.getString()+"\n");
                    } else // Length not available...
                    {
                        System.out.print("Leggo quantita'  dati sconosciuta...");
                        ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

                        // Read data one character at a time
                        int ch;
                        while ((ch = iStrm.read()) != -1) {
                            System.out.print(".");
                            bStrm.write(ch);
                        }

                        str = new String(bStrm.toByteArray());
                        bStrm.close();
                        txtRisultato.setString(txtRisultato.getString()+"\n\n*****Risposta del server: " + str + "***\n");
                        txtRisultato.setString(txtRisultato.getString()+"\n");
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                txtRisultato.setString(txtRisultato.getString()+"\nERRORE: non e' stato possibile collegarsi. Telefono fuori campo? (" + e.toString() +")");
                System.out.println("ERRORE: non e' stato possibile collegarsi. Telefono fuori campo?");
            } finally {
                // Clean up
                if (iStrm != null) {
                    try {
                        txtRisultato.setString(txtRisultato.getString()+"\nChiudo stream...");
                        iStrm.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (http != null) {
                    try {
                        txtRisultato.setString(txtRisultato.getString()+"\nChiudo connessione...");
                        http.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            txtRisultato.setString(txtRisultato.getString()+"\nConnessione terminata.\n");
        }
    }

public String getMese(String data) {
        int trovato, i;
        String[] mese = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dec"};
        trovato = 99;
        for (i = 0; i <= 11; i++) {
            System.out.println(data.substring(4, 7) + " " + (mese[i]));
            if (data.substring(4, 7).equals(mese[i])) {
                trovato = i + 1;
                i = 12;
            }
        }
        if (trovato < 10) {
            return ("0" + trovato);
        } else {
            return ("" + trovato);
        }
    }
           
public void getLogin() {
        System.out.println("Leggo dati di login...");
        //splStart.setText("Caricamento dati login..");
        try {
            InputStream is = null;
            int MAXLEN = 50;
            byte[] data = new byte[MAXLEN];
            String contenuto;

            is = getClass().getResourceAsStream("login.txt");
            if (is != null) {
                is.read(data, 0, MAXLEN);  // Legge tutto il file.  
                contenuto = new String(data, 0, MAXLEN);
                int fineuser = contenuto.indexOf('\n') - 1;
                int iniziopass = fineuser + 2;
                int finepass = contenuto.indexOf("\n",iniziopass) - 1;
                System.out.println("File='" + contenuto + "'");
                System.out.println("fineuser=" + fineuser);
                System.out.println("iniziopass=" + iniziopass);
                System.out.println("finepass=" + finepass);
                user = contenuto.substring(0, fineuser);
                pass = contenuto.substring(iniziopass, finepass);
                is.close();
                System.out.println(user + "," + pass);
            } else {
                System.out.println("Errore nell'accesso al file.");
                txtRisultato.setString(txtRisultato.getString()+"\nErrore nell'accesso al file.");
            }
        } catch (java.io.IOException ex) {
            System.out.println("Eccezione: errore generico nella lettura.");
            txtRisultato.setString(txtRisultato.getString()+"\nEccezione: errore generico nella lettura.");
            ex.printStackTrace();
        }
        System.out.println("Fatto.");
        //splStart.setText("Caricamento dati login copmpletato.");
    }
             
public void getChannels() {
        System.out.println("Leggo liste canali/stazioni..");
        //splStart.setText("Caricamento liste...");
        try {
            InputStream is = null;
            int MAXLEN = 10000;
            byte[] data = new byte[MAXLEN];
            String contenuto;
            String chan;

            // Memorizza canali TV
            System.out.println("########TV#########");
            is = getClass().getResourceAsStream("tv.txt");
            if (is != null) {  
                contenuto = new String(data, 0, is.read(data, 0, MAXLEN));// Legge tutto il file.
                NumTV = 0;
                while (contenuto.length()>0) {
                    int finechan = contenuto.indexOf('\n') - 1; // Trova fine riga.
                    chan = contenuto.substring(0, finechan); // Memorizza canale.
                    TVChannelName[NumTV] = chan; // (Numerazione inizia da zero)
                    NumTV++;
                    contenuto = contenuto.substring(finechan+2, contenuto.length()); // Cancella canale appena letto.
                }
                is.close();       
                System.out.println("Canali TV: "+Integer.toString(NumTV));
           } else {
                System.out.println("Errore nell'accesso alla lista dei canali TV.");
                txtRisultato.setString(txtRisultato.getString()+"\nErrore nell'accesso alla lista dei canali TV.");
           }
            
            // Memorizza canali radio
            System.out.println("########Radio#########");
            is = getClass().getResourceAsStream("radio.txt");
            if (is != null) {  
                NumRadio = 0;
                contenuto = new String(data, 0, is.read(data, 0, MAXLEN));// Legge tutto il file.
                while (contenuto.length()>0) {
                    int finechan = contenuto.indexOf('\n') - 1; // Trova fine riga.
                    chan = contenuto.substring(0, finechan); // Memorizza canale.
                    RadioChannelName[NumRadio] = chan; // (Numerazione inizia da zero)
                    NumRadio++;                    
                    contenuto = contenuto.substring(finechan+2, contenuto.length()); // Cancella canale appena letto.
                }
                is.close();       
                System.out.println("Canali radio: "+Integer.toString(NumRadio));
           } else {
                System.out.println("Errore nell'accesso alla lista dei canali Radio.");
                txtRisultato.setString(txtRisultato.getString()+"\nErrore nell'accesso alla lista dei canali Radio.");
            }
            
        } catch (java.io.IOException ex) {
            System.out.println("Eccezione: errore generico nella lettura dell'elenco canali Radio/TV.");
            txtRisultato.setString(txtRisultato.getString()+"\nEccezione: errore generico nella lettura dell'elenco canali Radio/TV.");
            ex.printStackTrace();
        }
        System.out.println("Fatto.");
        //splStart.setText("Caricamento canali completato.");
}

public void getOtherLists() {
        System.out.println("Leggo liste canali/stazioni..");
        //splStart.setText("Caricamento liste...");
        try {
            InputStream is = null;
            int MAXLEN = 10000;
            byte[] data = new byte[MAXLEN];
            String contenuto;
            String riga;

            // Memorizza formati di registrazione
            System.out.println("######## FORMATI #########");
            is = getClass().getResourceAsStream("formati.txt");
            if (is != null) {  
                contenuto = new String(data, 0, is.read(data, 0, MAXLEN));// Legge tutto il file.
                int Num = 0;
                while (contenuto.length()>0) {
                    int fineriga = contenuto.indexOf('\n') - 1; // Trova fine riga.
                    riga = contenuto.substring(0, fineriga); // Memorizza riga.
                    System.out.println(riga);
                    lstFormato.append(riga, null);
                    Num++;
                    contenuto = contenuto.substring(fineriga+2, contenuto.length()); // Cancella canale appena letto.
                }
                is.close();       
                System.out.println("Formati: "+Integer.toString(Num));
            }
            // Memorizza tabella conversione formati tra WEB e PHP
            System.out.println("######## TABELLA #########");
            is = getClass().getResourceAsStream("convert.txt");
            if (is != null) {  
                contenuto = new String(data, 0, is.read(data, 0, MAXLEN));// Legge tutto il file.
                int Num = 0;
                while (contenuto.length()>0) {
                    int fineriga = contenuto.indexOf('\n') - 1; // Trova fine riga.
                    riga = contenuto.substring(0, fineriga); // Memorizza riga.
                    System.out.println(Integer.toString(Num) + "->" + riga);
                    Num++;
                    ConvForm[Num] = Integer.valueOf(riga); // (Numerazione da 1)
                    contenuto = contenuto.substring(fineriga+2, contenuto.length()); // Cancella canale appena letto.
                }
                is.close();       
                System.out.println("Formati: "+Integer.toString(Num));
            }
            // Memorizza periodi di conservazione possibili
            System.out.println("######## CONSERVAZIONE #########");
            is = getClass().getResourceAsStream("conserv.txt");
            if (is != null) {  
                contenuto = new String(data, 0, is.read(data, 0, MAXLEN));// Legge tutto il file.
                int Num = 0;
                while (contenuto.length()>0) {
                    int fineriga = contenuto.indexOf('\n') - 1; // Trova fine riga.
                    riga = contenuto.substring(0, fineriga); // Memorizza riga.
                    System.out.println(riga);
                    lstConservazione.append(riga, null);
                    Num++;
                    contenuto = contenuto.substring(fineriga+2, contenuto.length()); // Cancella canale appena letto.
                }
                is.close();       
                System.out.println("Conservazione: "+Integer.toString(Num));
            }
            // Memorizza tipi di ripetizione possibili
            System.out.println("######## RIPETIZIONE #########");
            is = getClass().getResourceAsStream("ripetiz.txt");
            if (is != null) {  
                contenuto = new String(data, 0, is.read(data, 0, MAXLEN));// Legge tutto il file.
                int Num = 0;
                while (contenuto.length()>0) {
                    int fineriga = contenuto.indexOf('\n') - 1; // Trova fine riga.
                    riga = contenuto.substring(0, fineriga); // Memorizza riga.
                    System.out.println(riga);
                    lstRipetizioni.append(riga, null);
                    Num++;
                    contenuto = contenuto.substring(fineriga+2, contenuto.length()); // Cancella canale appena letto.
                }
                is.close();       
                System.out.println("Ripetizione: "+Integer.toString(Num));   
           } else {
                System.out.println("Errore nell'accesso alle liste.");
                txtRisultato.setString(txtRisultato.getString()+"\nErrore nell'accesso alle liste.");
           }          
      } catch (java.io.IOException ex) {
            System.out.println("Eccezione: errore generico nella lettura delle liste.");
            txtRisultato.setString(txtRisultato.getString()+"\nEccezione: errore generico nella lettura delle liste.");
            ex.printStackTrace();
        }
        System.out.println("Fatto.");
        //splStart.setText("Caricamento liste completato.");
        switchDisplayable(null, getFrmImmissioneDati());    
}

   public void estrazioneDati() {
       //DEBUG FIX
       System.out.println(lstCanale.getSelectedIndex());
        canale = lstCanale.getString(lstCanale.getSelectedIndex());
        titolo = txtTitolo.getString();
        formato = Integer.valueOf(Integer.toString(lstFormato.getSelectedIndex() + 1));
        ripetizione = lstRipetizioni.getSelectedIndex() + 1;
        conservazione = lstConservazione.getSelectedIndex() + 1;

        // Appoggiandosi a Calendar estraggo data e ora a
        // prescindere dalle impostazioni internazionali:

        Calendar cal = Calendar.getInstance();
        cal.setTime(dtStart.getDate());
        String InizioMinuto = addZero(cal.get(cal.MINUTE));
        String InizioOra = addZero(cal.get(cal.HOUR_OF_DAY));
        String InizioGiorno = addZero(cal.get(cal.DAY_OF_MONTH));
        String InizioMese = addZero((cal.get(cal.MONTH) + 1));
        String InizioAnno = (cal.get(cal.YEAR) + "").substring(2,4); // solo ultime cifre
        
        cal.setTime(dtEnd.getDate());
        String FineMinuto = addZero(cal.get(cal.MINUTE));
        String FineOra = addZero(cal.get(cal.HOUR_OF_DAY));
        String FineGiorno = addZero(cal.get(cal.DAY_OF_MONTH));
        String FineMese = addZero(cal.get(cal.MONTH) + 1);
        String FineAnno = (cal.get(cal.YEAR) + "").substring(2,4); // solo ultime cifre

        StringaInizio = "%22" + InizioAnno + "-" + InizioMese + "-" + InizioGiorno + "%20" + InizioOra + ":" + InizioMinuto + ":00%22";
        StringaFine = "%22" + FineAnno + "-" + FineMese + "-" + FineGiorno + "%20" + FineOra + ":" + FineMinuto + ":00%22";

        System.out.println("Dati immessi:");
        System.out.println("canale: " + canale);
        System.out.println("Titolo:" + titolo);
        System.out.println("Formato:" + lstFormato.getString(formato.byteValue() - 1));
        System.out.println("Ripetizione:" + lstRipetizioni.getString(ripetizione - 1));
        System.out.println("Conservazione:" + lstConservazione.getString(conservazione - 1));
        System.out.println("Inizio: " + InizioOra + ":" + InizioMinuto + " " + InizioGiorno + "/" + InizioMese + "/" + InizioAnno);
        System.out.println("Fine: " + FineOra + ":" + FineMinuto + " " + FineGiorno + "/" + FineMese + "/" + FineAnno);

      /*  System.out.println("Ora=" + cal.get(cal.HOUR_OF_DAY));
        System.out.println("Minuto=" + cal.get(cal.MINUTE));
        System.out.println("Giorno=" + cal.get(cal.DAY_OF_MONTH));
        System.out.println("Mese=" + (cal.get(cal.MONTH) + 1));
        System.out.println("Anno=" + cal.get(cal.YEAR));*/
        System.out.println("Estrazione dati terminata.");
    }

     public String addZero(int num) {
        if (num < 10) {
            return "0" + num;
        } else {
            return "" + num;
        }
    }
    
    public Integer convert(Integer formato) {
        // converte indice formato da form a URL
        formato = ConvForm[formato.byteValue()];
        return formato;    
}
    
        public static String replace(String _text, String _searchStr, String _replacementStr) {
        // String buffer to store str
        StringBuffer sb = new StringBuffer();

        // Search for search
        int searchStringPos = _text.indexOf(_searchStr);
        int startPos = 0;
        int searchStringLength = _searchStr.length();

        // Iterate to add string
        while (searchStringPos != -1) {
            sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
            startPos = searchStringPos + searchStringLength;
            searchStringPos = _text.indexOf(_searchStr, startPos);
        }

        // Create string
        sb.append(_text.substring(startPos, _text.length()));

        return sb.toString();
    }
    
    public void aggiornaFormConferma() {
        String stringa;
        stringa = "Titolo: " + titolo + "\nCanale: "+ canale + "\nFormato: "+ formato;
        stringa = stringa + "\nRipetizioni: " + lstRipetizioni.getString(ripetizione-1 );
        stringa = stringa + "\nConservazione: " + lstConservazione.getString(conservazione-1 );
        stringa = stringa + "\nRipetizioni: " + lstRipetizioni.getString(ripetizione-1 );
        stringa = stringa + "\nInizio: " + StringaInizio;
        stringa = stringa + "\nFine: " + StringaFine;
        System.out.println(stringa);
        txtRiepilogo.setString(stringa);
    }

    public void impostaCanali(int t) {
        lstCanale.append("Attendere...", null); // Crea primo canale solo per avvisare di attesa necessaria.
        lstCanale.setSelectedIndex(0, true); // Seleziona per default primo canale.          
        if (t == KVIDEO)
        {
            for (int i=1; i<NumTV; i++) {
                lstCanale.append(TVChannelName[i], null); 
            }
            lstCanale.set(0, TVChannelName[0], null); // Mette nome vero in primo canale
        }else {
            for (int i=0; i<NumRadio; i++) {
                lstCanale.append(RadioChannelName[i], null);    
            }
            lstCanale.set(0, RadioChannelName[0], null); // Mette nome vero in primo canale
       }
     switchDisplayable(null, getFrmImmissioneDati());  
     txtTitolo.setString("Inserire titolo");
    }
    public void salvaLogin() {

    }
}